<?php

namespace App\Http\Controllers;
use DB;
use App\Http\Requests\WzconfigPostRequest;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CarController extends Controller
{
		public function postChe(Request $request){
			//dd($request->all());
			//提取数据
			$data=$request->only(['id','num']);
			//检测当前商品是否已经存在与购物车中
			if($this->check($data['id'])){
				//如果存在就修改数量
				$goods = session('list');
				foreach($goods as $k=>$v){
					if($v['id']==$data['id']){

						$goods[$k]['num']+=$data['num'];
					}
					
				}

				//将更新后的数据重新存入session
				session(['list'=>$goods]);
				echo 1;
			}else{
			//将当前数据压入到cart
			$request->session()->push('list',$data);
			echo 1;
			}

		}

		//检测方法
		private function check($id){
			$goods=session('list');
			if(empty($goods)){
				return false;
			}
			foreach($goods as $k=>$v){
				if($v['id']==$id){
					//商品存在购物车中
					return true;

				}
			}

			//商品不存在返回false
			return false;
		}

		public function getList(){
			// 用户id
			$id = session('id');
			// dd($id);
			//提取当前所有的购物车商品提取书本数和书本id
			$goods=session('list');
			$gid = $goods['0']['id'];
			$gnum = $goods['0']['num'];
			// dd($gnum);

			$data=[];
			foreach($goods as $k=>$v){
				$tem = DB::table('goods')->where('id',$v['id'])->first();
				// dd($tem);
				$tem->num=$v['num'];
				// dd($tem->num);


				// 书本id 书本名  书本单价
				$data['id']=$tem->id;
				$data['uname']=$tem->name;
				$data['price']=$tem->price;
				//dd($tem);
			}
				$data['num'] = $gnum;
			// dd($data);
			  
			return view('home.car.car',['goods'=>$data,'uid'=>$id]);
		}


		//清空session
		public function getClear(){
			session()->forget('list');
		}
		        	
	    //删除购物车物品
		public function postDelete(Request $request){
			// dd($request -> input('id'));
			$id = $request -> input('id');
			 

     	$res = DB::table('goods')->where('name',$id)->delete();
     	if($res){
            echo 1;
     	}else{
     		echo 2;
     	}
     }

  
}
